package com.wxj.bank.module.utils;

import com.wxj.bank.module.constant.Constants;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author shengtao
 * @Description: 签名工具
 * @date 2018/12/05 12:43
 */
public class SignUtils {


    /**
     * map参数加签
     *
     * @param map 加签原参数
     * @return
     */
    public static String signMD5(Map<String,String> map){
        String source = createMap(map);
        if(StringUtils.isNotBlank(source)){
            String sign = DigestUtils.md5Hex(source);
            return sign;
        }
        return "";
    }

    public static boolean validSignMD5(Map<String,String> params){

        String sign = params.get("sign");

        params.remove("sign");

        String newSign = signMD5(params);

        if(StringUtils.isNotBlank(newSign)
                && StringUtils.isNotBlank(sign)
                && newSign.equals(sign)){
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

    public static String createMap(Map<String,String> params){

        if(MapUtils.isNotEmpty(params)){

            List<String> keys = new ArrayList<String>(params.keySet());

            Collections.sort(keys);

            StringBuilder builder = new StringBuilder();

            final int[] i = {0};

            keys.stream().forEach(key->{
                builder.append(key).append(Constants.SYMBOL_EQUAL).append(params.get(key));
                if(i[0] != (keys.size() - 1)){
                    builder.append(Constants.SYMBOL_AND);
                }
                i[0]++;
            });
            return builder.toString();
        }

        return "";
    }

}
